<template>
  <div class="edit">
    <h3 class="title is-3">发布一篇新的文章</h3>
    <el-form ref="form" :model="form" :rules="rules" label-width="80px" label-position="left">
      <el-form-item label="文章分类" prop="category">
        <el-input v-model="form.category" placeholder="请输入文章类别"></el-input>
       <!-- <el-select v-model="form.category" placeholder="请选择文章分类">
          <el-option  v-for="cate in categorys" :key="cate.id" :label="cate.get('name')" :value="cate">{{ cate.get('name') }}</el-option>
        </el-select>-->
      </el-form-item>

      <el-form-item label="文章标题" prop="title">
        <el-input v-model="form.title" placeholder="请输入文章标题"></el-input>
      </el-form-item>

      <div class="el-form-item is-required" :class="{ 'is-error': validate.error }" >
        <label class="el-form-item__label">上传图片</label>
        <div class="el-form-item__content  img">
          <input type="file" value="上传图片" class="avatar-input" accept="*.png,*.jpg,*.jpeg,*gif"  @change.stop="addAvatar">
          <span class="avatar"  v-if="this.imgUrl" :style="{ backgroundImage: 'url(' + this.imgUrl + ')'}"></span>
          <span v-else class="avatar">没有上传图片哦！！</span>
          <div v-if="validate.error" class="el-form-item__error">图片怎能没有内容呢？</div>
        </div>
      </div>

      <div class="el-form-item is-required" :class="{ 'is-error': validate.error }">
        <label class="el-form-item__label">文章内容</label>
        <div class="el-form-item__content">
          <div id="editor"></div>
          <div v-if="validate.error" class="el-form-item__error">正文怎能没有内容呢？</div>
        </div>
      </div>

      <div class="oprator right">
        <el-button class="submit" type="primary" @click="submit" @keyup.enter="submit">发布文章</el-button>
      </div>

    </el-form>
  </div>
</template>

<script>

  import { mapState } from 'vuex';
  import lrz from 'lrz'
  let editor = null;

  export default {

    name: 'create',

    data () {
      return {
        article: null,
        imgUrl:'',
       /* categorys: [],*/
        form: {
          category: '',
          title: '',
        },
        rules: {
          title: [
            { required: true, message: "必须填写标题哦!", trigger: 'blur' },
          ],
          category: [
            { required: true, message: "必须填写分类哦!", trigger: 'blur' },
          ],

        },
        validate: {
          error: false
        }
      };
    },
    created(){
     /* this.getCategory();*/
      this.getArticle();//得到文章
    },
    mounted(){
      this.initEditor();
      window.q = this;
    },
    computed: {
      ...mapState(['user']),
      text: {
        get(){
          return editor.$txt.html();
        },
        set(html){
          return editor.$txt.html(html)
        }
      }
    },
    methods: {
      addAvatar() {
        let that = this;
        lrz(event.currentTarget.files[0])
          .then(function (rst) {
            that.imgUrl = rst.base64;
            console.log("图片")
            console.log( that.imgUrl )
          })
          .catch(function (err) {
            this.$message.error('错了哦。');
          });
      },
      getContent(){
        return editor.$txt.html();
      },
      setContent(html){
        return editor.$txt.html(html)
      },
      getArticle(){
        const id = this.$route.params.id;//得到文章的ID号
        let q = new this.$api.SDK.Query('Article');
        q.include('category');
        q.get(id).then((article) => {
          this.article = article;

          this.form.title = article.get('title');//标题
          this.form.category = article.get('category_name');//类别
          this.imgUrl = article.get('article_img');
   /*       const cid = article.get('category').id;//分类
          const cate = article.get('category');//分类*/
        /*  this.form.category = this.cate;*/
       /*   this.wait(this.categorys.length).then(() => {
            const index = this.categorys.findIndex(c => c.id == cid);
            this.form.category = this.categorys[index];//表单分类
          })*/
          this.wait(editor).then(() => {
            this.setContent(article.get('content'))//重置文章
          });

          this.$Progress.finish();

        })
      },
      wait(flag){
        console.log(flag)
        return new Promise((reslove, reject) => {
          let timer = null;
          if (flag) {
            reslove()
          }else{
            timer = setInterval(() => {
              if (!flag) {return;}
              reslove()
              clearInterval(timer);
            }, 500)

          }
        })
      },
      initEditor(){
        let E = window.wangEditor;
        editor = new E('editor')

        editor.config.menus = $.map(wangEditor.config.menus, function(item, key) {
          // https://www.kancloud.cn/wangfupeng/wangeditor2/113975 请看这里
          if (item === 'location') {
            return null;
          }
          return item;
        });

        editor.create();

        editor.onchange = () => {
          this.validateContent();
        }

      },
   /*   getCategory(){
        const cq = new this.$api.SDK.Query('Category');
        cq.find().then((categorys) => {
          this.categorys = categorys;
        }).catch(console.error)
      },*/

      validateContent(){
        if (this.getContent() == '<p><br></p>') {
          this.validate.error = true;
          $('.wangEditor-container').css({borderColor:'red'})
          return;
        }

        this.validate.error = false;
        $('.wangEditor-container').css({borderColor:'#ccc'})
      },

      setArticle(){
        const article = this.article;
        article.set('author', this.user);
        article.set('title', this.form.title);
        article.set('content', this.getContent());
        article.set('category_name', this.form.category);
        article.set('article_img', this.imgUrl);
        return article;
      },


      save(article){
        article.save().then((article) => {
          console.log(article);
          const message =  `文章《${article.get('title')}》修改成功`;
          this.$message({message, type: 'success'})
          this.$router.replace({name:"ArticleShow", params: { id: article.id }});
        }).catch(console.error);
      },

      submit(){
        this.$refs.form.validate((valid) => {
          this.validateContent();
          if (valid) {
            const article = this.setArticle();
            this.save(article);
          } else {
            console.log('error submit!!');
            this.$message.error('错了哦，您填写的信息有错误，请按照提示修改。');
            return false;
          }
        })

      }
    },
  };
</script>

<style lang="css" scoped>
  .oprator{
    margin-top: 20px;
    float: right;
  }
  #editor{
    height: 600px;
    overflow: scroll;
    overflow-x: hidden;
  }
  .edit{
    width: 90%;
    margin: 0 auto;
    text-align: center;
  }
  .avatar-input{
    cursor: pointer;
    background-color: #cccccc;
  }
  .avatar{
    margin-left: 20px;
    display: inline-block;
    width: 70px;
    height: 70px;
    background-size: cover;
    border-radius: 50%;
  }
  .el-button{
    background-color: black;
    color: #ffffff;

  }
</style>
